<?php

	function getPipePos($n, $line)
	{
		$pos = 0;
		for ($i = 0; $i < $n; $i++)
		{
			$pos = strpos($line, "|", $pos + 1);
		}
		return $pos;
	}

	function getRank($line)
	{
		$length = getPipePos(1, $line);
		return substr($line, 0, $length);
	}

	function getField($s, $e, $line)
	{
		$start = getPipePos($s, $line) + 1;
		$length = getPipePos($e, $line) - $start;
		return substr($line, $start, $length);
	}

	$razzfilename = "razzballrankings";
	$razzfile = file_get_contents("raw/" . $razzfilename);
	$razzlines = explode("\n", $razzfile);

	$overallfilename = "espnyahooaggr.data";
	$overallfile = file_get_contents("out/" . $overallfilename);
	$overalllines = explode("\n", $overallfile);


	$AGGREGATED_LIST = "Y!|E|RZ|NAME|TEAM|POS|GMS|MIN|lFGM|lFGA|lFG%|lFTM|lFTA|lFT%|l3PTM|lPTS|lREB|lAST|lST|lBLK|lTO|pFGM|pFGA|pFG%|pFTM|pFTA|pFT%|p3PTM|pPTS|pREB|pAST|pST|pBLK|pTO|a3PTM|aPTS|aREB|aAST|aST|aBLK|aTO";
	$i = 0;

	foreach($overalllines as $overallline)
	{
		if ($i > 0)
		{
			$name = getField(2, 3, $overallline);
			$rank = getRank($overallline);
			$razzrank = 201;
			$found = false;
			foreach($razzlines as $razzline)
			{
				$posInOverall = strpos($razzline, $name);
				if ($posInOverall !== false)
				{
					$razzrank = getRank($razzline);
					break;
				}
			}
			$AGGREGATED_LIST .= "\n" . substr_replace($overallline, "|" . $razzrank, getPipePos(2, $overallline), 0);
		}
		$i++;
	}
	if (file_put_contents("out/espnyahoorazz.data", $AGGREGATED_LIST) !== false)
	{	
		echo "<h3>Successfully aggregated out/$razzfilename to out/$overallfilename.</h3>" .
			"<h3>Processed data is at out/espnyahoorazz.data.</h3>";
		echo "<iframe src='out/espnyahoorazz.data' width='100%' height='80%'>";
	}
	else
	{
		echo "<h3>Error processing raw data.</h3>";
	}
?>